//
//  SZLSelectWineFriendsViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/9/14.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLSelectWineFriendsViewController.h"
#import "GoodsManageTableViewCell.h"
#import "SZLAccountHelper.h"
#import "WineNewFriendsViewController.h"
#import "WineFriendsNetwork.h"
#import "MBProgressHUD+MJ.h"
#import "UIAlertView+Entension.h"
#import <Masonry.h>
#import "SZLAddressBookViewController.h"
#import "SZLNearWineFriendsController.h"

@interface SZLSelectWineFriendsViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>

@property (nonatomic, weak) UISearchBar *searchBar;
@property (nonatomic,strong) UIScrollView *scroll;
@property (nonatomic, strong) UITableView *friendsTab;
@property (nonatomic, strong) UITableView *groupsTab;
@property (nonatomic, strong) UITableView *applyTab;
@property (nonatomic,strong) NSArray *titles;//没有搜索时显示手机联系人 附近酒友
@property (nonatomic, assign) NSInteger selectIndex;//segment选中
@property (nonatomic, assign) BOOL isSearch;//点击了搜索后

@property (nonatomic,weak) UIView *bgView;//最上面容器
@property (nonatomic,weak) UISegmentedControl *control;
@property (nonatomic,strong) NSMutableArray *resultArray;//查找好友的结果
@property (nonatomic,strong) NSMutableArray *applyArray;//申请列表
@property (nonatomic,assign) BOOL isFirstSelectApply;


@end

@implementation SZLSelectWineFriendsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"新的酒友";
    
    self.titles = @[@"添加手机联系人",@"附近酒友"];
    self.selectIndex = 0;
    self.isSearch = NO;
    [self createView];
    self.isFirstSelectApply = YES;
}
- (void)createView
{
    UIView *bgView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, ScreenW, 100))];
    bgView.backgroundColor = RGBColorOne(240);
    self.bgView = bgView;
    bgView.clipsToBounds = YES;
    [self.view addSubview:bgView];
    NSArray *controlArray = @[@"找酒友",@"找酒群",@"酒友申请"];
    
    UISegmentedControl *control = [[UISegmentedControl alloc] initWithItems:controlArray];
    control.frame = (CGRectMake(10, 5, ScreenW-20, 35));
    control.backgroundColor = [UIColor whiteColor];
    control.selectedSegmentIndex = 0;
    control.tintColor = WineColor;
    [control addTarget:self action:@selector(segementSelect:) forControlEvents:(UIControlEventValueChanged)];
    [bgView addSubview:control];
    
    UISearchBar *search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(control.frame)+10, ScreenW, 40)];
    search.placeholder = @"请输入酒友的昵称或手机号";
    search.delegate = self;
    self.searchBar = search;
    [bgView addSubview:search];
    [self.view addSubview:search];
    [self.view addSubview:self.scroll];
    [self.scroll addSubview:self.friendsTab];
    [self.scroll addSubview:self.groupsTab];
    [self.scroll addSubview:self.applyTab];
}
- (void)segementSelect:(UISegmentedControl *)control
{
    self.selectIndex = control.selectedSegmentIndex;
    [self clearSearchResult];
    if (control.selectedSegmentIndex == 0) {
        self.bgView.height = 100;
        self.scroll.y = 100;
        self.scroll.height = ScreenH-64-100;
        self.searchBar.placeholder = @"请输入酒友的昵称或手机号";
        self.scroll.contentOffset = CGPointMake(0, 0);
    }else if (control.selectedSegmentIndex == 1){
        self.bgView.height = 100;
        self.scroll.y = 100;
        self.scroll.height = ScreenH-64-50;
        self.searchBar.placeholder = @"请输入酒群的昵称或号码";
        self.scroll.contentOffset = CGPointMake(ScreenW, 0);
    }else if (control.selectedSegmentIndex == 2){
        self.bgView.height = 50;
        self.scroll.y = 50;
        self.scroll.height = ScreenH-64-50;
        self.scroll.contentOffset = CGPointMake(ScreenW*2, 0);
        if (self.isFirstSelectApply) {
            [self getApplyLists];
            self.isFirstSelectApply = NO;
        }
    }
}
- (void)clearSearchResult
{
    [self hideNoDataView];//隐藏没有数据提示
    self.searchBar.text = @"";
    if (self.selectIndex == 0) {
        [self.resultArray removeAllObjects];
        self.isSearch = NO;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.friendsTab) {
        if (self.isSearch) {
            return 90;
        }
        return 44;
    }
    return 90;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.friendsTab) {
        if (self.resultArray.count == 0&&!self.isSearch) {
            return 2;
        }
        return self.resultArray.count;
    }else if (tableView == self.groupsTab) {
        return 0;
    }
    return self.applyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.friendsTab) {
        if (self.resultArray.count == 0&&!self.isSearch) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
            cell.textLabel.text = self.titles[indexPath.row];
            cell.textLabel.textColor = [UIColor grayColor];
            cell.textLabel.font = Font(15);
            return cell;
        }else{
            GoodsManageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GoodsManageTableViewCell class])];
            cell.userModel = self.resultArray[indexPath.row];
            return cell;
        }
    }else if (tableView == self.groupsTab) {
        return nil;
    }
    GoodsManageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GoodsManageTableViewCell class])];
    cell.userModel = self.applyArray[indexPath.row];
    __WEAK
    cell.agreeAddBlock = ^(EaseUserModel *userModel,UIButton *btn){
        [weakSelf agreeAddFriends:userModel btn:btn];
    };
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == self.friendsTab) {
        if (self.resultArray.count == 0&&!self.isSearch) {
            if (indexPath.row == 0) {
                SZLAddressBookViewController *addressVc = [[SZLAddressBookViewController alloc]init];
                [self.navigationController pushViewController:addressVc animated:YES];
            }else{
                SZLNearWineFriendsController *nearVc = [[SZLNearWineFriendsController alloc]init];
                [self.navigationController pushViewController:nearVc animated:YES];
            }
        }else{
            WineNewFriendsViewController *wfVc = [[WineNewFriendsViewController alloc] init];
            wfVc.userModel = self.resultArray[indexPath.row];
            [self.navigationController pushViewController:wfVc animated:YES];
        }
    }else if (tableView == self.groupsTab) {
        
    }else{
    }
}
#pragma mark ----------------------搜索好友---------------------
- (void)beginSearchFriends
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"token"] = [SZLAccountHelper shareInstance].token;
    params[@"searchContent"] = self.searchBar.text;
    [self showWaiter];
    __WEAK
    [WineFriendsNetwork selectFirendsWithParame:params response:^(BOOL success, NSString *msg, NSArray *friends) {
        [weakSelf hideWaiter];
        if (success) {
            [weakSelf.resultArray removeAllObjects];
            [weakSelf hideNoDataView];
            if (friends.count == 0) {
                [weakSelf showNoDataView:self.friendsTab.frame title:@"没有符合条件的酒友"];
            }
            [weakSelf.resultArray addObjectsFromArray:friends];
            [weakSelf.friendsTab reloadData];
        }else{
            [MBProgressHUD showError:msg toView:weakSelf.view];
        }
    }];
}
//获取申请列表
- (void)getApplyLists
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"token"] = [SZLAccountHelper shareInstance].token;
    __WEAK
    [self showWaiter];
    [WineFriendsNetwork getApplyFirendListsWithParame:params response:^(BOOL success, NSString *msg, NSArray *friends) {
        [weakSelf hideWaiter];
        if (success) {
            [weakSelf.applyArray removeAllObjects];
            if (friends.count == 0) {
                [self showNoDataView:CGRectMake(0, 50, ScreenW, ScreenH-64-50) title:@"暂无好友申请消息"];
                return ;
            }
            [weakSelf.applyArray addObjectsFromArray:friends];
            [self.applyTab reloadData];
        }else{
            [MBProgressHUD showError:msg toView:weakSelf.view];
        }
    }];
}
//同意添加好友
- (void)agreeAddFriends:(EaseUserModel *)userModel btn:(UIButton *)btn
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否同意添加好友" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    [alert handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
        if (btnIndex == 1) {
            btn.hidden = YES;
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"token"] = [SZLAccountHelper shareInstance].token;
            params[@"friendMobilePhone"] = userModel.buddy;
            params[@"addFriendApplyId"] = @(userModel.addFriendApplyId);
            __WEAK
            [weakSelf showWaiter];
            [WineFriendsNetwork agreeAddfriendsWithParame:params response:^(BOOL success, NSString *msg) {
                [weakSelf hideWaiter];
                if (success) {
                    [MBProgressHUD showSuccess:@"已同意添加好友" toView:weakSelf.view];
                    userModel.isApply = NO;
                }else{
                    [MBProgressHUD showError:msg toView:weakSelf.view];
                }
            }];
        }
    }];
}
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.isSearch = YES;
    [self beginSearchFriends];
    [self searchBarResignFirstResponse];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [self.resultArray removeAllObjects];
    self.isSearch = NO;
    [self.friendsTab reloadData];
    [self searchBarResignFirstResponse];
}
- (void)searchBarResignFirstResponse
{
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:NO animated:YES];
}
- (UIScrollView *)scroll
{
    if (!_scroll) {
        _scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 100, ScreenW, ScreenH-64-100)];
        _scroll.contentSize = CGSizeMake(ScreenW*3, 0);
        _scroll.pagingEnabled = YES;
        _scroll.scrollEnabled = NO;
        _scroll.backgroundColor = [UIColor whiteColor];
    }
    return _scroll;
}
- (UITableView *)friendsTab
{
    if (!_friendsTab) {
        _friendsTab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, self.scroll.height)];
        _friendsTab.delegate = self;
        _friendsTab.dataSource = self;
        _friendsTab.tableFooterView = [[UIView alloc]init];
        [_friendsTab registerNib:[UINib nibWithNibName:NSStringFromClass([GoodsManageTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([GoodsManageTableViewCell class])];
        [_friendsTab registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    }
    return _friendsTab;
}
- (UITableView *)applyTab
{
    if (!_applyTab) {
        _applyTab = [[UITableView alloc] initWithFrame:CGRectMake(ScreenW*2, 0, ScreenW, self.scroll.height+50)];
        _applyTab.delegate = self;
        _applyTab.dataSource = self;
        _applyTab.tableFooterView = [[UIView alloc]init];
        [_applyTab registerNib:[UINib nibWithNibName:NSStringFromClass([GoodsManageTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([GoodsManageTableViewCell class])];
    }
    return _applyTab;
}
- (UITableView *)groupsTab
{
    if (!_groupsTab) {
        _groupsTab = [[UITableView alloc] initWithFrame:CGRectMake(ScreenW, 0, ScreenW, self.scroll.height)];
        _groupsTab.delegate = self;
        _groupsTab.dataSource = self;
        _groupsTab.tableFooterView = [[UIView alloc]init];
        [_groupsTab registerNib:[UINib nibWithNibName:NSStringFromClass([GoodsManageTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([GoodsManageTableViewCell class])];
    }
    return _groupsTab;
}
- (NSMutableArray *)resultArray
{
    if (!_resultArray) {
        _resultArray = [[NSMutableArray alloc] init];
    }
    return _resultArray;
}
- (NSMutableArray *)applyArray
{
    if (!_applyArray) {
        _applyArray = [[NSMutableArray alloc] init];
    }
    return _applyArray;
}

@end
